<template>
  <div class="todo-tip-container" id="todo-tip-container">
    <!-- 待办事项 -->
    <a-popover
      trigger="click"
      v-model="visible"
      placement="bottomLeft"
      overlayClassName="nebula-notice-popover"
      :getPopupContainer="getPopupContainer"
      @visibleChange="visibleChange"
    >
      <a slot="content">
        <div class="nebula-notice-container" v-if="todoData.length > 0">
          <div class="header">
            消息通知
            <span @click="gotoDaiban()">更多>></span>
          </div>
          <div class="notice-list-container">
            <a-tabs @change="handelTabChange" v-model="activekey">
              <a-tab-pane
                force-render
                :key="item.menuCode"
                v-for="item in todoData"
              >
                <span slot="tab">
                  {{ item.menuName }}（{{ item.dataCount }}）
                </span>
                <div class="notice-list-body">
                  <div
                    class="notice-list"
                    v-for="(todo, idx) in item.dataList"
                    :key="idx"
                    @click="gotoDaiban()"
                  >
                    <div class="index">({{ idx + 1 }})</div>
                    <div class="details">
                      <div class="title">
                        {{ todo.push_comment || todo.pushComment }}
                      </div>
                      <div class="date">{{ todo.updateTime }}</div>
                    </div>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </div>
        <div class="nebula-notice-empty" v-else>
          <a-empty />
        </div>
      </a>
      <div class="notice-warp">
        <bj-icon-font type="daiban_" color="#fff" :size="20"></bj-icon-font>
        <span class="nums" v-if="todoTotal > 0">{{
          todoTotal > 99 ? "99+" : todoTotal
        }}</span>
      </div>
    </a-popover>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { getLoginData, saveData } from "@/tools";
import { notificationTip } from "@/utils";
import { queryPending } from "@/api/todo";
export default {
  props: {},
  data() {
    return {
      visible: false,
      activekey: "",
      todoListData: [],
      todoCount: 0,
      wsInstance: "",
      params: {},
    };
  },
  computed: {
    ...mapGetters(["organization", "todoActiveKey", "todoData", "todoTotal"]),
  },
  watch: {
    organization: {
      handler(val) {
        if (JSON.stringify(val) == "{}") {
          return;
        }
        let { tenantTypeValue } = val;
        if (tenantTypeValue == 3) {
          this.params = val;
          this.getTodoData();
        } else {
          this.clearData();
        }
      },
      immediate: true,
      deep: true,
    },
  },

  mounted() {},
  methods: {
    //popover切换
    visibleChange(e) {
      this.activekey = this.todoActiveKey;
    },
    //待办tabs切换
    handelTabChange(key) {
      saveData("TODO_ACTIVEKEY", key || null);
    },

    //去处理
    gotoDaiban() {
      saveData("CURRENT_MENU", {
        menuCode: "PAGE_TODO",
        menuName: "待办事项",
        path: "/todo",
      });
      saveData("SERVICE_SOURCE", []);
      this.visible = false;
    },

    //清空数据
    clearData() {
      this.todoListData = [];
      this.todoCount = 0;
      saveData("TODO_DATA", []);
      saveData("TODO_TOTAL", 0);
      saveData("TODO_ACTIVEKEY", null);
      localStorage.removeItem("TODO_ACTIVEKEY");
    },

    //存入数据
    saveTodo(data = {}, type) {
      let {
        result: { retList = [], totalCount = 0 },
      } = data;
      let source = retList.filter((v) => v.menuCode);
      this.todoListData = source ?? [];
      this.todoCount = totalCount ?? 0;
      //数据存入vuex
      saveData("TODO_DATA", this.todoListData || []);
      saveData("TODO_TOTAL", this.todoCount || 0);
      this.$store.dispatch("setStoreState", {
        TODO_ACTIVEKEY: this.todoListData[0]?.menuCode || null,
      });
      //判断Tab切换Key
      let active = localStorage.getItem("TODO_ACTIVEKEY");
      if (active != null) {
        saveData("TODO_ACTIVEKEY", active);
      }
      if (type == 1) {
        this.closeSocket();
        this.connectSocket();
      }
    },

    //查询待办列表
    getTodoData(type = 1) {
      let { userId } = getLoginData();
      let { tenantCode } = this.params;
      queryPending({
        userId,
        tenantCode,
      })
        .then((res) => {
          let { data } = res;
          this.saveTodo(data, type);
        })
        .catch((_) => {
          this.clearData();
        });
    },

    //关闭websocket
    closeSocket() {
      if (this.wsInstance) {
        this.wsInstance.close();
        this.wsInstance = null;
      }
    },

    //连接websocket
    connectSocket() {
      const { host } = require("@/environment/index");
      let { userId } = getLoginData();
      this.wsInstance = new WebSocket(
        `${host.websocket}/user/api/webSocket/${userId}`
      );
      //连接成功回调
      this.wsInstance.onopen = () => {
        let { userId } = getLoginData();
        let requestBody = {
          userId: userId,
        };
        this.wsInstance.send(JSON.stringify(requestBody));
      };

      //接受服务端发送的数据
      this.wsInstance.onmessage = (msg) => {
        notificationTip("info", msg.data);
        this.getTodoData(2);
        this.$store.dispatch("setStoreState", {
          TODO_WEBSOCKET: Date.now(),
        });
      };

      //socket连接关闭时回调
      this.wsInstance.onclose = () => {
        console.log("Socket已被关闭---------------->>>>>");
      };
      //socket连接关闭时回调
      this.wsInstance.onerror = (err) => {
        console.log(err, "Socket连接错误-------->>>>>>");
      };
    },

    getPopupContainer() {
      return document.getElementById("todo-tip-container");
    },
  },
};
</script>

<style lang="less" scoped>
.todo-tip-container {
  /deep/.nebula-notice-popover {
    .ant-popover-inner-content {
      padding: 0;
    }
    .nebula-notice-container {
      width: 400px;
      .header {
        font-size: 18px;
        color: #333;
        padding: 20px 16px 0 16px;
        text-align: left;
        display: flex;
        justify-content: space-between;
        span {
          color: var(--primary-color);
          font-size: 14px;
          margin-top: 2px;
          cursor: pointer;
          &:hover {
            text-decoration: underline;
          }
        }
      }
      .notice-list-body {
        max-height: 180px;
        .custom-scrollbar();
        .notice-list {
          margin-bottom: 15px;
          font-size: 14px;
          padding: 0 22px;
          cursor: pointer;
          display: flex;
          border-bottom: 1px solid #fff;
          .title {
            color: #2b2c30;
            padding-bottom: 2px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            width: 330px;
          }
          .date {
            color: #89898b;
          }
          .index {
            flex-shrink: 0;
            width: 25px;
          }
          .details {
            flex: 1;
          }
        }
      }
      /deep/.ant-tabs {
        margin-top: 5px;
        .ant-tabs-tab {
          padding: 10px 0 14px 0;
          font-size: 14px;
        }
        .ant-tabs-ink-bar {
          display: none !important;
        }
        .ant-tabs-nav-scroll {
          // text-align: center;
          padding: 0 20px;
        }
      }
    }
    .nebula-notice-empty {
      width: 300px;
      height: 200px;
    }
  }
  .notice-warp {
    color: #fff;
    position: relative;
    margin-top: 4px;
    margin-right: 20px;
    margin-left: 30px;
    cursor: pointer;
    .nums {
      position: absolute;
      top: -5px;
      left: 12px;
      background: #f45353;
      font-size: 12px;
      border-radius: 10px;
      padding: 0 5px;
    }
    .bj-icon {
      font-size: 20px;
    }
  }
}
</style>
